import os

from utils.drivers.database.engine import AsyncEngine, AsyncSession
from utils.drivers.database.models import params, product_type, product, news_type, news, page, page_images, message
from utils.drivers.database.models.message import MessageModel
from utils.helper import load_yaml
from utils.paths import RootPath


async def init_database():
    """
    创建数据库
    """
    process = 0

    async with AsyncEngine.begin() as conn:
        await conn.run_sync(params.Base.metadata.create_all)
        process += 1
        yield process, "创建数据库会话"

        await conn.run_sync(product_type.Base.metadata.create_all)
        process += 1
        yield process, "创建产品类型表"

        await conn.run_sync(product.Base.metadata.create_all)
        process += 1
        yield process, "创建产品表"

        await conn.run_sync(news_type.Base.metadata.create_all)
        process += 1
        yield process, "创建新闻类型表"

        await conn.run_sync(news.Base.metadata.create_all)
        process += 1
        yield process, "创建新闻表"

        await conn.run_sync(page.Base.metadata.create_all)
        process += 1
        yield process, "创建页面表"

        await conn.run_sync(page_images.Base.metadata.create_all)
        process += 1
        yield process, "创建页面图片表"

        await conn.run_sync(message.Base.metadata.create_all)
        process += 1
        yield process, "创建留言表"

    async with AsyncSession() as session:
        async with session.begin():
            # 数据表
            db_params = load_yaml(os.path.join(RootPath, "utils", "drivers", "database", "init", "db_params.yaml"))
            process += 1
            yield process, "加载数据表初始化数据"

            for param in db_params:
                session.add(params.Params(
                    key=param["key"],
                    value=param["value"],
                    type=param["type"]
                ))
                process += 1
                yield process, f"[数据] {param['desc']}"

            # 产品分类
            db_product_type = load_yaml(
                os.path.join(RootPath, "utils", "drivers", "database", "init", "db_product_type.yaml"))
            process += 1
            yield process, "加载产品类型表初始化数据"

            for pt in db_product_type:
                session.add(product_type.ProductType(
                    key=pt["key"],
                    name=pt["name"],
                    sort=pt["sort"]
                ))
                process += 1
                yield process, f"[产品类型] {pt['name']}"

            # 产品
            db_product = load_yaml(os.path.join(RootPath, "utils", "drivers", "database", "init", "db_product.yaml"))
            process += 1
            yield process, "加载产品表初始化数据"

            for p in db_product:
                session.add(product.Product(
                    number=p["number"],
                    name=p["name"],
                    name_en=p["name_en"],
                    product_type=p["product_type"],
                    brief=p["brief"],
                    brief_en=p["brief_en"],
                    description=p["description"],
                    description_en=p["description_en"],
                    status=p["status"],
                    cover=p["cover"],
                    push=p["push"]
                ))
                process += 1
                yield process, f"[产品] {p['name']}"

            # 新闻分类
            db_news_type = load_yaml(
                os.path.join(RootPath, "utils", "drivers", "database", "init", "db_news_type.yaml"))
            process += 1
            yield process, "加载新闻类型表初始化数据"

            for nt in db_news_type:
                session.add(news_type.NewsType(
                    key=nt["key"],
                    name=nt["name"],
                    sort=nt["sort"]
                ))
                process += 1
                yield process, f"[新闻分类] {nt['name']}"

            # 新闻
            db_news = load_yaml(os.path.join(RootPath, "utils", "drivers", "database", "init", "db_news.yaml"))
            process += 1
            yield process, "加载产品表初始化数据"

            for n in db_news:
                session.add(news.News(
                    title=n["title"],
                    title_en=n["title_en"],
                    news_type=n["news_type"],
                    brief=n["brief"],
                    brief_en=n["brief_en"],
                    text=n["text"],
                    text_en=n["text_en"],
                    status=n["status"],
                    cover=n["cover"]
                ))
                process += 1
                yield process, f"[新闻] {n['title']}"

            # 页面
            db_page = load_yaml(os.path.join(RootPath, "utils", "drivers", "database", "init", "db_page.yaml"))
            process += 1
            yield process, "加载页面表初始化数据"

            for p in db_page:
                session.add(page.Page(
                    page=p["page"],
                    type=p["type"],
                    content=p["content"],
                    content_en=p["content_en"]
                ))
                process += 1
                yield process, f"[页面] {p['page']}"

            # 页面图片
            db_page_images = load_yaml(os.path.join(RootPath, "utils", "drivers", "database", "init", "db_page_images.yaml"))
            process += 1
            yield process, "加载页面图片表初始化数据"

            for i, pi in enumerate(db_page_images):
                session.add(page_images.PageImages(
                    key=pi["key"],
                    sort=pi["sort"],
                    title=pi["title"],
                    title_en=pi["title_en"]
                ))
                if i % 10 == 0:
                    process += 1
                yield process, f"[页面图片] {pi['title']}"

            # 页面图片
            db_message = load_yaml(os.path.join(RootPath, "utils", "drivers", "database", "init", "db_message.yaml"))
            process += 1
            yield process, "加载消息表初始化数据"

            for i, m in enumerate(db_message):
                m = MessageModel(id=0, **m)
                session.add(message.Message(
                    username=m.username,
                    tel=m.tel,
                    email=m.email,
                    ip=m.ip,
                    content=m.content,
                    status=m.status.value,
                ))
                process += 1
                yield process, f"[测试消息] {m.content}"

            await session.commit()


if __name__ == '__main__':
    import asyncio


    async def run():
        async for i in init_database():
            print(i)


    asyncio.run(run())
